import React, {Component} from 'react';
import http from "../../http";

class SaveSelect extends Component {
	constructor(props) {
		super(props);
		this.state = {
			categoryList: [],
			subCategoryList: []
		}
	}

	componentDidMount() {
		this.getCategoryList()
	}

	componentWillUpdate(nextProps) {
		if (this.props.categoryParentId !== nextProps.categoryParentId) {
			this.getSubCategoryList(nextProps)
		}
	}

	getCategoryList = () => {
		http.getProductCategoryList().then(res => {
			if (res.data) {
				this.setState({
					categoryList: res.data
				})
			}
		})
	};

	getSubCategoryList = props => {
		http.getProductCategoryList(props.categoryParentId).then(res => {
			if (res.data) {
				this.setState({
					subCategoryList: res.data
				})
			}
		})
	};

	render() {
		return (
			<div className="col-md-10">
				<select
					value={this.props.categoryParentId}
					onChange={e => this.props.changeCategoryParentId(e.target.value)}
					className="form-control cate-select col-md-5"
					disabled={this.props.disabled}
				>
					<option value={0}>请选择一级品类</option>
					{
						this.state.categoryList.map(item => {
							return (
								<option
									key={item.id}
									value={item.id}
								>{item.name}</option>
							)
						})
					}
				</select>
				{
					this.state.subCategoryList.length > 0
						?
						<select
							value={this.props.categoryId}
							onChange={e => this.props.changeCategoryId(e.target.value)}
							className="form-control cate-select col-md-5"
							disabled={this.props.disabled}
						>
							<option value={0}>请选择二级品类</option>
							{
								this.state.subCategoryList.map(item => {
									return (
										<option
											key={item.id}
											value={item.id}
										>{item.name}</option>
									)
								})
							}
						</select>
						:
						''
				}
			</div>
		);
	}
}

export default SaveSelect;